package jianzhiOffer;
//剑指 Offer 12. 矩阵中的路径
public class Num12_exist {
    public boolean exist(char[][] board, String word) {
        //转为字符数组
        char [] words = word.toCharArray();
        //遍历二维数组
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (dfs(board,words,i,j,0)){
                    return true;
                }
            }
        }
        return false;

    }
    //深度优先遍历
    private boolean dfs(char[][] board, char[] word, int i, int j, int k) {
        //判断条件
        if (i >= board.length || i < 0 || j >= board[0].length || j < 0 || board[i][j] != word[k]){
            return false;
        }
        //完全匹配
        if (k == word.length - 1)return true;
        board[i][j] = '\0';//走到这说明board[i][j] != words[k]相等 、、覆盖
        boolean res = dfs(board, word, i + 1, j, k + 1) || dfs(board, word, i - 1, j, k + 1) ||
                dfs(board, word, i, j + 1, k + 1) || dfs(board, word, i , j - 1, k + 1);
        board[i][j] = word[k];
        return res;
    }
}
